﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

namespace Dapper.ExpressionExtension.Resolvers
{
    /// <summary>
    /// 默认主键解析器
    /// </summary>
    public class DefaultKeyPropertyResolver : IKeyPropertyResolver
    {
        /// <summary>
        /// 解析主键，id和【KeyAttribute】的列作为主键
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ColumnPropertyInfo[] ResolveKeyProperties(Type type)
        {
            var keyProps = ResolverHelper
                .Properties(type).Select(x => x.Property)
                .Where(p => string.Equals(p.Name, "Id", StringComparison.OrdinalIgnoreCase) || p.GetCustomAttribute<KeyAttribute>() != null)
                .ToArray();

            if (keyProps.Length == 0)
            {
                throw new InvalidOperationException($"missing the key properties for type '{type.FullName}'.");
            }

            return keyProps.Select(p => new ColumnPropertyInfo(p, true)).ToArray();
        }
    }
}
